﻿using System.Collections.Generic;
using System.Xml.Linq;
using SharePhone.Common;
using SharePhone.Common.Web;
using SharePhone.Provider.WebServices;
using SharePhone.Utility;

namespace SharePhone.Provider
{
    public delegate void GetWebCollectionCompleted(List<SPWeb> webs);

    public delegate void GetWebCompleted(SPWeb web);

    public class WebProvider
    {
        public static void GetWebCollection(GetWebCollectionCompleted callBack, string webUrl, ContextSettings settings)
        {
            var client = new SPWebService(webUrl, settings.Credentials);
            client.GetWebCollectionCompleted += (object sender, RequestCompleteEventArgs e) =>
                                                    {
                                                        List<SPWeb> webs = ParseWebCollectionXML(e.Result, settings);
                                                        callBack(webs);
                                                    };
            client.GetWebCollectionAsync();
        }

        public static void GetWeb(GetWebCompleted callBack, string webUrl, ContextSettings settings)
        {
            var client = new SPWebService(webUrl, settings.Credentials);
            client.GetWebCompleted += (object sender, RequestCompleteEventArgs e) =>
                                          {
                                              SPWeb web = ParseWebXML(e.Result, settings);
                                              callBack(web);
                                          };
            client.GetWebAsync(webUrl);
        }

        #region Internal parsers

        private static SPWeb ParseWebXML(XElement xml, ContextSettings settings)
        {
            string url = XmlUtility.GetAttributeValue(xml, "Url");
            var web = new SPWeb(url);

            web.Title = XmlUtility.GetAttributeValue(xml, "Title");
            web.Description = XmlUtility.GetAttributeValue(xml, "Description");
            web.Language = XmlUtility.GetAttributeValue(xml, "Language");
            web.Theme = XmlUtility.GetAttributeValue(xml, "Theme");
            web.Settings = settings;
            return web;
        }


        private static List<SPWeb> ParseWebCollectionXML(XElement xml, ContextSettings settings)
        {
            IEnumerable<XElement> webs = xml.Elements();
            var webList = new List<SPWeb>();
            foreach (XElement web in webs)
            {
                SPWeb spWeb = ParseWebXML(web, settings);
                webList.Add(spWeb);
            }
            return webList;
        }

        #endregion
    }
}